package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class ClientProfile {

	private static class MessageHandler extends DefaultHandler {
		private String clientId;
		private Map<String, Integer> programs;

		public MessageHandler() {
			clientId = new String();
			programs = new HashMap<String, Integer>();
		}

		@Override
		public void startElement(String uri, String localName, String qName,
				Attributes attributes) throws SAXException {
			if (qName.equals("client-profile")) {
				if (attributes.getLength() == 1) {
					clientId = attributes.getValue("id");
				}
			} else {
				if (qName.equals("program")) {
					if (attributes.getLength() == 2) {
						programs.put(attributes.getValue("title"),
								Integer.parseInt(attributes.getValue("time")));
					}
				}
			}
		}
	}

	private MessageHandler handler;

	public void buildClientProfile(String message)
			throws ParserConfigurationException, SAXException, IOException {
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		InputSource is = new InputSource(new StringReader(message));
		handler = new MessageHandler();
		parser.parse(is, handler);
	}

	public String getClientId() {
		return handler.clientId;
	}

	public Map<String, Integer> getPrograms() {
		return handler.programs;
	}

}
